package com.sparrow.common.ai.behaviortree.task.impl;

import com.sparrow.common.ai.behaviortree.def.BTNodeStatus;
import com.sparrow.common.ai.behaviortree.BehaviorContext;
import com.sparrow.common.ai.behaviortree.node.BehaviorNode;
import com.sparrow.common.ai.behaviortree.node.impl.SequenceNode;
import com.sparrow.common.ai.behaviortree.task.BehaviorTask;
import java.util.ArrayList;
import java.util.List;

/**
 * 逐个顺序执行子节点，直到一个子节点失败。
 * 如果所有子节点都成功，整个 Sequence 成功。
 * 任意一个子节点失败，整个 Sequence失败
 *
 */
public class SequenceTask extends BehaviorTask {

    private final List<BehaviorTask> childTasks = new ArrayList<>();
    private final SequenceNode node;
    private int currentIndex = 0;

    public SequenceTask(SequenceNode node) {
        this.node = node;
        for (BehaviorNode child : node.getChildren()) {
            this.childTasks.add(child.createTask());
        }
    }

    @Override
    public BTNodeStatus tick(BehaviorContext context, long now, long delta) {
        while (currentIndex < childTasks.size()) {
            BehaviorTask task = childTasks.get(currentIndex);
            BTNodeStatus status = task.tick(context, now, delta);
            if (status == BTNodeStatus.RUNNING) {
                return BTNodeStatus.RUNNING;
            }
            if (status == BTNodeStatus.FAILURE) {
                currentIndex = 0;
                return BTNodeStatus.FAILURE;
            }
            currentIndex++;
        }
        currentIndex = 0;
        return BTNodeStatus.SUCCESS;
    }

    @Override
    public String toString() {
        return "SequenceTask{" +
                "childTasks=" + childTasks +
                ", node=" + node +
                ", currentIndex=" + currentIndex +
                '}';
    }
}
